const {exec} = require("../db/mysql")
const xss = require("xss")

const getList = (author,keyword)=>{
  //拼接sql语句 1=1是为了占位
  
  let sql=`select * from blogs where 1=1 `
  if(author){

    
    sql+=`and author="${author}"`
  }
  if(keyword){
    sql+=`and title like "%${keyword}%"`
  }
  sql+=`order by createtime desc`
  
  return exec(sql)
  
}
const getDetail=(id)=>{
  const sql=`select * from blogs where id=${id}`
  return exec(sql)
}
const newBlog=(blogData)=>{
  const title=xss(blogData.title);
  const content=blogData.content;
  const createtime=blogData.createtime;
  const author=blogData.author
  
  const sql=`insert into blogs(title,content,createtime,author) values("${title}","${content}","${createtime}","${author}")`
  return exec(sql).then(data=>{
    
    return data.insertId
    
  })
  
  // return exec(sql)
}
const updateBlog=(id,blogData={})=>{
  const title=blogData.title
  const content=blogData.content
  let sql=`update blogs set title="${title}",content="${content}" where id = "${id}"`
  return exec(sql).then(data=>{
    
    return data.affectedRows
  })
}

const delBlog=(id,author)=>{
   //这里要加双重保障 也就是加一次作者的where 为了不让作者删除别人的博客
  let sql=`delete from blogs where id = ${id} and author = "${author.author}"`
  
  return exec(sql).then(rest=>{
    return rest.affectedRows
  })
}
const delUser=(id,realname)=>{
  //这里要加双重保障 也就是加一次作者的where 为了不让作者删除别人的博客
  let sql=`update users set state = 0 where id = ${id} and realname = "${realname.realname}"`
  return exec(sql).then(rest=>{
    return rest.affectedRows
  })
}

module.exports={
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
  delUser
}